package io.sunny.platform.ai.deepseek.service;

import io.micrometer.common.util.StringUtils;
import io.sunny.platform.ai.deepseek.model.CodeGenerationRequest;
import io.sunny.platform.ai.deepseek.model.CodeGenerationResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.validation.ValidationException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @Author SUNNY
 * @Date 2025/11/29 19:43
 * @PackageName: io.sunny.platform.ai.deepseek.service
 * @Description: 智能代码助手
 * @Version 1.0
 */
@Slf4j
@Service
public class CodeGenerationService {

    @Autowired
    private ChatClient chatClient;

    private final PromptTemplate codePromptTemplate = new PromptTemplate("""
            你是一个资深{language}开发专家，请根据以下需求生成高质量的代码：
            
            需求描述：
            {requirement}
            
            具体要求：
            1. 严格遵循{styleGuide}开发规范
            2. 包含完整的异常处理机制
            3. 添加清晰的中文注释，重要逻辑需说明设计意图
            4. 考虑性能优化和线程安全
            5. 提供必要的单元测试示例
            
            请直接返回代码，不需要额外的解释说明。
            """);

    public CodeGenerationResult generateCode(CodeGenerationRequest request) {
        try {
            // 参数验证
            validateRequest(request);

            // 构建提示词
            Map<String, Object> variables = Map.of(
                    "language", request.getLanguage(),
                    "requirement", request.getRequirement(),
                    "styleGuide", request.getStyleGuide()
            );

            Prompt prompt = codePromptTemplate.create(variables);

            // 调用AI服务
            long startTime = System.currentTimeMillis();
            String content = chatClient.prompt(prompt).call().content();
            long contTime = System.currentTimeMillis() - startTime;

            log.info("代码生成完成，耗时：{}ms，语言：{}，需求：{}", contTime, request.getLanguage(), request.getRequirement());

            return CodeGenerationResult.success(content, contTime);

        } catch (ValidationException e) {
            log.warn("参数验证失败：{}", e.getMessage());
            return CodeGenerationResult.fail("参数验证失败：" +  e.getMessage());
        } catch (Exception e) {
            log.error("代码生成异常：{}", e.getMessage(), e);
            return CodeGenerationResult.fail("系统异常，请稍后重试");
        }
    }

    /**
     * 批量代码生成
     */
    @Async
    public CompletableFuture<List<CodeGenerationResult>> batchGenerateCode(List<CodeGenerationRequest> requests) {
        List<CompletableFuture<CodeGenerationResult>> futures = requests.stream()
                .map(request -> CompletableFuture.supplyAsync(() -> generateCode(request),
                        Executors.newCachedThreadPool()))
                .toList();
        return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                .thenApply(v -> futures.stream()
                        .map(CompletableFuture::join)
                        .toList());
    }

    private void validateRequest(CodeGenerationRequest request) {
        if (StringUtils.isBlank(request.getRequirement())) {
            throw new ValidationException("需求描述不能为空");
        }
        if (StringUtils.isBlank(request.getLanguage())) {
            throw new ValidationException("编程语言不能为空");
        }
    }
}
